<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>07_axios中取消请求和拦截器结合</title>
    <script src="js/axios.min.js"></script>
</head>
<body>
<button id="btn1">点我获取测试数据</button>
<button id="btn2">点我取消请求</button>
<script type="text/javascript">

    const btn1 = document.getElementById('btn1')
    const btn2 = document.getElementById('btn2')

    // CancelToken：能为一次请求“打标识”
    const {CancelToken, isCancel} = axios
    let cancel

    // 请求拦截器
    axios.interceptors.request.use(config => {
        if (cancel) cancel('多次请求！！')
        config.cancelToken = new CancelToken(c => { // c：是一个函数，调用 c 就可以关闭本次请求
            cancel = c
        })
        return config
    })

    // 响应拦截器
    axios.interceptors.response.use(
        response => {
            return response.data
        },
        error => {
            if (isCancel(error)) {
                // 如果进入判断，证明：是用户取消了请求
                console.log('用户取消了请求，原因是：', error.message);
            } else {
                console.log('失败了', error);
            }
            return new Promise(() => {
            })
        }
    )

    btn1.onclick = async () => {
        const result = await axios({
            url: 'http://localhost:5000/test2',
            params: {delay: 3000},
        })
        console.log(result)
    }

    btn2.onclick = () => {
        cancel('单纯就是不想要了')
    }
</script>
</body>
</html>
